/*
 用户基本信息维护页面
 create by 业哥 on 2017/09/08
 */
<template>
	<div id="user_admin" class="app-container">
		<div class="wrapper user">
			<el-col :span="9" class="warp-main">
				<el-col :span="24">
					<!-- 用户查询搜索条件输入.start -->
					<div class="el-bar">
						<p>
							<i class="iconfont icon-users"></i>查询条件</p>
						<el-form :inline="true" class="demo-form-inline">
							<el-form-item label="查关键字">
								<el-input v-model="listQuery.queryKey" placeholder="eg:登录名,角色名,真实名字"></el-input>
							</el-form-item>
							<el-form-item>
								<el-button icon="el-icon-search" type="primary" @click="queryUserBase" >查询</el-button>
							</el-form-item>
						</el-form>
					</div>
					<!-- 用户查询搜索条件输入.end -->

					<!-- 用户查询列表.start -->
					<div class="el-bar" style="margin-top:10px;" ref="queryUserDiv" >
						<p>
							<i class="iconfont icon-users"></i>查询列表
							<span>共<span>{{queryTotal}}</span>条</span>
						</p>
						<el-table v-loading="loadingUserDataTable" :data="tableData" @row-click="queryUserTableRowClick" highlight-current-row border style="width: 100%;margin-top:10px;">
							<el-table-column prop="loginName" label="登陆名">
							</el-table-column>
							<el-table-column prop="role" label="角色名称">
							</el-table-column>
						</el-table>
					</div>
					<!-- 分页.start -->
					<div v-show="usrListLoading" class="pagination-container" style="text-align:center;background:#fff;">
						<el-pagination
							@current-change="handleCurrentChange"
							:current-page.sync="listQuery.page"
							:page-size="listQuery.pageSize"
							layout="prev, pager, next"
							:total="queryTotal">
						</el-pagination>
					</div>
					<!-- 分页.end -->
					<!-- 用户查询列表.end -->
				</el-col>
			</el-col>
			<el-col :span="15" class="warp-main user-form" style="padding-left:30px;">
				<!-- 用户基本信息登记.start -->
				<div class="el-bar">
					<p>
						<i class="iconfont icon-users"></i>用户明细</p>
					<el-form :label-position="labelPosition" label-width="80px" autoComplete="on" :model="userBase" ref="userBase" :rules="userBaseRules" class="form-top">
						<el-form-item label="登陆名" prop="loginName">
							<el-input :disabled="disableLoginNameInput" name="loginName" type="text" v-model="userBase.loginName" autoComplete="on" placeholder="请输入登陆名"></el-input>
						</el-form-item>
						<el-form-item label="登陆密码" prop="loginPassword">
							<el-input :disabled="disableLoginPasswordInput" name="loginPassword" type="password" v-model="userBase.loginPassword" autoComplete="on" placeholder="请输入登陆密码"></el-input>
						</el-form-item>
						<el-form-item label="真实姓名" prop="name">
							<el-input name="name" type="text" v-model="userBase.name" autoComplete="on" placeholder="请输入真实姓名"></el-input>
						</el-form-item>
						<el-form-item label="性别" prop="sex">
							<el-select name="sex" v-model="userBase.sex" placeholder="请选择">
								<el-option v-for="item in sexArr" :key="item.value" :label="item.label" :value="item.value">
								</el-option>
							</el-select>
						</el-form-item>
						<el-form-item label="手机号" prop="phone">
							<el-input :maxlength="11" name="phone" type="text" v-model="userBase.phone" autoComplete="on" placeholder="请输入手机号"></el-input>
						</el-form-item>
						<el-form-item label="邮箱" prop="email">
							<el-input name="email" type="text" v-model="userBase.email" autoComplete="on" placeholder="请输入邮箱"></el-input>
						</el-form-item>
						<el-form-item label="登录时长" prop="sessionExpireTime">
							<el-input name="sessionExpireTime" type="text" v-model="userBase.sessionExpireTime" autoComplete="on" placeholder="请输入登录时长:单位,秒"></el-input>
						</el-form-item>
						<el-form-item label="选择角色" prop="role">
							<el-select name="role" v-model="userBase.role" @visible-change="loadRoleSelectBox" placeholder="请选择">
								<el-option v-for="item in roleArr" :key="item.id" :label="item.name" :value="item.id">
								</el-option>
							</el-select>
						</el-form-item>
						<div class="form-btn">
							<el-form-item>
								<el-button type="primary" class="iconfont icon-xinzeng" @click.native.prevent="addUserBase">新增</el-button>
								<el-button type="success" class="iconfont icon-baocun" @click.native.prevent="saveUserBase">保存</el-button>
								<el-button type="danger" icon="el-icon-delete" :disabled="isDelete" @click="deleteUserBase">删除</el-button>
							</el-form-item>
						</div>
					</el-form>
				</div>
				<!-- 用户基本信息登记.end -->

			</el-col>
		</div>
	</div>
</template>


<script>

import { validateEmail, validatePhone,validateNumber} from '@/utils/validate';

export default {
	name: 'userBase',
	data() {

		/* 1:声明校验.开始 */

		// 登录账号校验
		const validateLoginName = (rule, value, callback) => {
			if (value.length < 2) {
				callback(new Error('登录账号不能为空'));
			} else {
				callback();
			}
		};
		// 登录密码校验
		const validateLoginPassword = (rule, value, callback) => {
			if (value.length < 6) {
				callback(new Error('密码不能少于6位'));
			} else {
				callback();
			}
		};
		// 真实姓名校验
		const validateName = (rule, value, callback) => {
			if (value.length < 2) {
				callback(new Error('登录账号不能为空'));
			} else {
				callback();
			}
		};
		// 手机号码校验
		const _validatePhone = (rule, value, callback) => {
			if (!validatePhone(value)) {
				callback(new Error('请输入正确手机号码'));
			} else {
				callback();
			}
		};
		// 邮箱校验
		const _validateEmail = (rule, value, callback) => {
			if (!validateEmail(value)) {
				callback(new Error('请输入正确的邮箱'));
			} else {
				callback();
			}
		};
		// 登录时长
		const validateSessionExpireTime = (rule, value, callback) => {
			if (value.length < 1) {
				callback(new Error('登录时长不能为空'));
			} else {
                if (!validateNumber(value)) {
                    callback(new Error("非法参数"));
                } else {
                    callback();
                }
			}
		};
		// 性别校验
		const validateSex = (rule, value, callback) => {
			if (value.length < 1) {
				callback(new Error('请选择性别'));
			} else {
				callback();
			}
		};
		// 角色校验
		const validateRole = (rule, value, callback) => {
			if (value.length < 1) {
				callback(new Error('请选择角色'));
			} else {
				callback();
			}
		};

		/* 1:声明校验.结束 */

		/* 2:数据初始化.开始 */

		return {
			// 是否禁用登录账号输入框
			disableLoginNameInput: true,
			// 是否禁用登录密码账号输入框
			disableLoginPasswordInput: true,
			// 是否新增用户
			isAddUser: false,
			// 是否更新用户,
			isUpdateUser: false,
			// 搜索输入框初始化
			queryTotal: 0,
			// 是否显示分页插件
			usrListLoading: false,
			listQuery: {
          		page: 1,
				pageSize: 5,
				queryKey: ''
        	},
			// 搜索table数据初始化
			tableData: [],
			labelPosition: 'right',
			// 用户信息表单数据对象,初始化
			userBase: {
				id: '',
				loginName: '',
				loginPassword: '',
				name: '',
				phone: '',
				email: '',
				sex: '',
				role: '',
				sessionExpireTime: 1800
			},
			// 用户信息表单数据中性别,初始化
			sexArr: [{
				value: 0,
				label: '男'
			}, {
				value: 1,
				label: '女'
			}],
			// 用户信息表单数据中角色数据初始化
			roleArr: [],
			// 表单输入校验
			userBaseRules: {
				loginName: [
					{ required: true, trigger: 'blur', validator: validateLoginName }
				],
				loginPassword: [
					{ required: true, trigger: 'blur', validator: validateLoginPassword }
				],
				name: [
					{ required: true, trigger: 'blur', validator: validateName }
				],
				phone: [
					{ required: true, trigger: 'blur', validator: _validatePhone }
				],
				email: [
					{ required: true, trigger: 'blur', validator: _validateEmail }
				],
				sessionExpireTime: [
					{ required: true, trigger: 'blur', validator: validateSessionExpireTime }
				],
				sex: [
					{ required: true, trigger: 'blur', validator: validateSex }
				],
				role: [
					{ required: true, trigger: 'blur', validator: validateRole }
				]
			},
			// 删除按钮禁用
            isDelete: true,
            // 查询用户数据遮罩
            loadingUserDataTable: false,



			/* 2:数据初始化.结束 */

		}; // return end

	}, // data end
	created() {
		// 初始化角色选择下拉框
      this.loadRoleSelectBox();
      // 加载用户数据
      this.queryUserBase();
    },
	methods: {
		// 保存用户信息
		saveUserBase() {
			// 1: 判断是新增,还是更新用户信息
			// 2: 要更新用户信息,必须先通过左边的查询,得到用户的信息,再进行更新操作
			// 3: 更新用户信息操作,不对用户的登录账号和密码进行修改,要修改登录密码,用户自行进行修改
			// 校验
			this.$refs.userBase.validate(valid => {
				if (valid) {
					// 更新用户信息
					if (this.isUpdateUser) {
                        // 操作审计
                        this.userBaseInfo.setOperObjectName(this.userBase.name);
						this.httpClient.httpClientPatch(this.projectConfig.URL_API_USER_UPDATEUSER, this.userBase).then(res => {

							/* let _code = res.meta.code;
							let _message = res.meta.message;
							let _type = 'success';
							if (_code == this.projectConfig.CODE_OK) {
								// 清除表单数据
								this.$refs.userBase.resetFields();
								// 刷新搜索table
								this.listQuery.page = 1;
								this.listQuery.queryKey = '';
								this.queryUserBase();
							} else {
								_type = 'error';
							}
							// 弹框提示
							this.$message({
								showClose: true,
								message: _message,
								type: _type,
								duration: 5 * 1000
							}); */

							// 进来是200
							// 清除表单数据
							this.$refs.userBase.resetFields();
							// 刷新搜索table
							this.listQuery.page = 1;
							this.listQuery.queryKey = '';
							this.queryUserBase();
						});
					} // end of isUpdateUser

					// 新增用户信息
					if (this.isAddUser) {
                        // 操作审计
                        this.userBaseInfo.setOperObjectName(this.userBase.name);
						// 先判断用户是否存在
						this.httpClient.httpClientPost(this.projectConfig.URL_API_USER_VALIDATE_ACCOUNT, this.userBase).then(res => {
							//let _code = res.meta.code;
							let _code = res.data;
							let _message = res.meta.message;
							if (_code == this.projectConfig.CODE_OK) {
								// 用户存在
								// 弹框提示
								/* this.$message({
									showClose: true,
									message: this.userBase.loginName+',用户已经存在!',
									type: 'warning',
									duration: 5 * 1000
								}); */
								this.$notify({
									title: '警告',
									message: '用户已经存在:' + this.userBase.loginName,
									type: 'warning'
								});
							} else {
								// 新增
								this.httpClient.httpClientPost(this.projectConfig.URL_API_USER_ADDUSER, this.userBase).then(res => {
									/* let _code = res.meta.code;
									let _message = res.meta.message;
									let _type = 'success';
									if (_code == this.projectConfig.CODE_OK) {
										// 清除表单数据
										this.$refs.userBase.resetFields();
										// 刷新搜索table
										this.listQuery.page = 1;
										this.listQuery.queryKey = '';
										this.queryUserBase();
									} else {
										_type = 'error';
									}
									// 弹框提示
									this.$message({
										showClose: true,
										message: _message,
										type: _type,
										duration: 5 * 1000
									}); */
									// 进来就是200
									// 清除表单数据
									this.$refs.userBase.resetFields();
									// 刷新搜索table
									this.listQuery.page = 1;
									this.listQuery.queryKey = '';
									this.queryUserBase();

								});
							}
						});
					} // end of isAddUser

				} else {
					return false;
				}
			})

			/* this.$refs.userBase.validate(valid => {
				if (valid) {
					// 校验通过,请求后台,进行数据交换
					// 1:判断此操作为新增用户还是,修改已经存在的用户
					this.httpClient.httpClientPost(this.projectConfig.URL_API_USER_VALIDATE_ACCOUNT, this.userBase).then(res => {
						let _code = res.meta.code;
						let _message = res.meta.message;
						if (_code == this.projectConfig.CODE_OK) {
							// 状态码200,用户已经存在
							// 此操作为修改用户信息
							this.httpClient.httpClientPost(this.projectConfig.URL_API_USER_UPDATEUSER, this.userBase).then(res => {
								let _code = res.meta.code;
								let _message = res.meta.message;
								let _type = 'success';
								if (_code == this.projectConfig.CODE_OK) {
									// 清除表单数据
									this.$refs.userBase.resetFields();
								} else {
									_type = 'error';
								}

								// 弹框提示
								this.$message({
									showClose: true,
									message: _message,
									type: _type,
									duration: 5 * 1000
								});
							});
						} else {
							// 用户不存在
							// 新增用户
							this.httpClient.httpClientPost(this.projectConfig.URL_API_USER_ADDUSER, this.userBase).then(res => {
								let _code = res.meta.code;
								let _message = res.meta.message;
								let _type = 'success';
								if (_code == this.projectConfig.CODE_OK) {
									// 清除表单数据
									this.$refs.userBase.resetFields();
								} else {
									_type = 'error';
								}
								// 弹框提示
								this.$message({
									showClose: true,
									message: _message,
									type: _type,
									duration: 5 * 1000
								});

							});
						} // end of if

						// 刷新搜索table
						this.listQuery.page = 1;
						this.listQuery.queryKey = this.userBase.loginName;
						this.queryUserBase();
					});

				} else {
					// 检验不通过
					return false;
				}
			}) */
		},
		// 新增用户信息
		addUserBase() {
			// 清楚表单数据
			this.$refs.userBase.resetFields();
			// 解除登录账号输入框的禁用状态
			this.disableLoginNameInput = false;
			// 解除登录密码输入框的禁用状态
			this.disableLoginPasswordInput = false;
			// 新增
			this.isAddUser = true;
			this.isUpdateUser = false;
			// 禁用删除按钮
			this.isDelete = true;
		},
		// 查询搜索用户信息
		queryUserBase() {
			// loading
            //this.userBaseInfo.loadDom(this.$refs.queryUserDiv);
            // 开启遮罩
            this.loadingUserDataTable = true;
			// 发起请求
			this.httpClient.httpClientget(this.projectConfig.URL_API_USER_QUERY_USER,this.listQuery).then( res => {
				/* let _code = res.meta.code;
				if ( _code == this.projectConfig.CODE_OK) {
					this.tableData = [];
					// 查询成功,返回结果
					this.tableData = res.data.items;
					this.queryTotal = res.data.total;
					if (res.data.total > this.listQuery.pageSize) {
						// 显示分页插件
						this.usrListLoading = true;
					} else {
						// 关闭分页插件
						this.usrListLoading = false;
					}
				} else {
					// 查询失败
					// 弹框提示
					this.$message({
						showClose: true,
						message: '没有查询到用户信息,请重新查询',
						duration: 5 * 1000
					});
					// 清空table
					this.tableData = [];
					// 禁用删除按钮
                    this.isDelete = true;
                } */

                // 遮罩结束
                this.loadingUserDataTable = false;
				this.tableData = [];
				// 查询成功,返回结果
				this.tableData = res.data.items;
				this.queryTotal = res.data.total;
				if (res.data.total > this.listQuery.pageSize) {
					// 显示分页插件
					this.usrListLoading = true;
				} else {
					// 关闭分页插件
					this.usrListLoading = false;
				}

			}).catch(error => {
                // 遮罩结束
                this.loadingUserDataTable = false;
            });
		},
		// 分页搜索,当前页面改变触发事件
		handleCurrentChange(val) {
			// 获取当前是第几页
			this.listQuery.page = val;
			this.queryUserBase();
		},
		// 用户搜索table行点击事件
		queryUserTableRowClick: function (row, event, column)  {
			// 获得行的数据
			const _id = row.id; // 主键ID
			const _loginName = row.loginName; // 登录账号
			const _loginPassword= row.loginPassword; // 登录密码
			const _name = row.name; // 真实名字
			const _sex = row.sex; // 性别
			const _phone = row.phone; // 电话
			const _email = row.email; // 邮箱
			const _role = row.role; // 角色名
			const _roleId = row.roleId; // 角色ID
			const _sessionExpireTime = row.sessionExpireTime; // 登录时长

			// 赋值到右边的输入框中
			this.userBase.id = _id;
			this.userBase.loginName = _loginName;
			this.userBase.loginPassword = _loginPassword;
			this.userBase.name = _name;
			this.userBase.sex = _sex;
			this.userBase.phone = _phone;
			this.userBase.email = _email;
			this.userBase.sessionExpireTime = _sessionExpireTime;
			this.userBase.role = _roleId;


			if (_id.length > 0 && typeof _id != 'undefined') {
				// 解除禁用的删除按钮
				this.isDelete = false;
				// 禁用登录账号输入框
				this.disableLoginNameInput = true;
				this.disableLoginPasswordInput = true;
				// 可以进行更新操作
				this.isAddUser = false;
				this.isUpdateUser = true;
			}
		 },
		 // 加载角色下拉选择框
		 loadRoleSelectBox() {
			 this.httpClient.httpClientget(this.projectConfig.URL_API_USER_GET_ROLES,'').then( res => {
				 let _code = res.meta.code;
				 if	(_code == this.projectConfig.CODE_OK) {
					 // 加载下拉框
					 this.roleArr = res.data;
				 }
			 });
		 },
		 // 删除用户信息,根据用户的ID
		 deleteUserBase() {
			 // 获得用户的ID
			 let _userId = this.userBase.id;
			 if (_userId.length == 0 || typeof _userId == 'undefined') {
				 /* this.$message({
					showClose: true,
					message: '请选择一条用户信息',
					type: 'warning',
					duration: 5 * 1000
				}); */

				this.$notify.info({
					title: '消息',
					message: '请选择一条用户信息'
				});
			 } else {
				this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
        		}).then(() => {
                    // 操作审计
                    this.userBaseInfo.setOperObjectName(this.userBase.name);
					//let param = {id:this.userBase.id}
					let deleteUrl = this.projectConfig.URL_API_USER_DELETE_USER + '/' + this.userBase.id;
					// 执行删除操作
					this.httpClient.httpClientDelete(deleteUrl,'').then( res => {
						// 进来就是 200
						// 刷新搜索table
						this.listQuery.page = 1;
						this.listQuery.queryKey = '';
						this.queryUserBase();
					})
					// 清除表单数据
					this.$refs.userBase.resetFields();
				}).catch(() => {
        		});
			 }
		 },
		 // 选择命名空间的事件
		/* selectHeaderNamespaceRow() {
			console.log('select namespace user == ' + this.headerFormInline.namespace);
		} */

	}, // 方法集合 end
	/* computed: {
        getCurrentNamespace() {
            return this.$store.getters.namespace;
        }
    },
    watch: {
        getCurrentNamespace(val) {
			// 当选择选择头部空间下拉框的时候,触发事件
             // console.log('我在用户维护页面,监听空间选择=' + val);
        },

    } */
}
</script>
<style>
.user .el-form {
	margin-top: 12px;
}

.user-form .el-form-item {
	display: inline-block;
	margin-left: 40px;
}

.user-form .form-top {
	margin-top: 20px;
}

.user .el-select {
	width: 188px;
}

.user .form-btn {
	border-top: 1px solid #f0f0f0;
	padding-top: 20px;
	text-align: right;
}
.user .el-select>.el-input{
	width:172px;
}
</style>
